package com.example.myapplication_2.camera;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.Paint;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.AudioRecord;
import android.media.Image;
import android.media.ImageReader;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;


import com.baidu.speech.EventManager;
import com.example.myapplication_2.Main_Activity;
import com.example.myapplication_2.R;
import com.example.myapplication_2.util.OkHttpUtil;
import com.tencent.cos.xml.CosXmlService;
import com.tencent.cos.xml.CosXmlServiceConfig;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.listener.CosXmlProgressListener;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.transfer.UploadService;
import com.tencent.qcloud.core.auth.QCloudCredentialProvider;
import com.tencent.qcloud.core.auth.ShortTimeCredentialProvider;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import okhttp3.Response;
import okhttp3.Call;
import okhttp3.Callback;



@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class CustomCamera extends Activity {
    private AutoFitTextureView texture;

//    private ImageView takephoto;

//    private Switch change;

    private RadioButton auto;

    private RadioButton open;

    private RadioButton close;

    private RadioGroup flashRg;

    protected boolean enableOffline = false; // 测试离线命令词，需要改成true

    /*** 相机管理类*/
    CameraManager mCameraManager;

    /*** 指定摄像头ID对应的Camera实体对象*/
    CameraDevice mCameraDevice;

    private Button but_fan;
    private  Button but_cx;
    private  Button but_xyb;
    /**
     * 预览尺寸
     */
    private Size mPreviewSize;
    private int mSurfaceWidth;
    private int mSurfaceHeight;
    private AudioRecord audioRecord;
    private Button speak;//说话按钮
    private Paint paint;
    /**
     * The JPEG image
     * 要保存的图片
     */
    private Image mImage;
    /**
     * The file we save the image into.
     * 图片存储的路径
     */
    private File mFile;

    private String mFilePath = null;
    private String appid = "1256678596";  //上传图片的appid
    private String region = "ap-beijing";//上传图片的区域名
    private String imgUriInNet;//图片在服务器上的网络路径
    private String token = null;
    private String cuid = null;
    private File file;
    private Button play;
    private boolean isRecording = false;//false表示还没开始进行录制，
    private EventManager asr;
    private String POST_URL;

    /*** 打开摄像头的ID{@link CameraDevice}.*/
    private int mCameraId = CameraCharacteristics.LENS_FACING_FRONT;


    /*** 处理静态图像捕获的ImageReader。{@link ImageReader}*/
    private ImageReader mImageReader;

    /*** 用于相机预览的{@Link CameraCaptureSession}。*/
    private CameraCaptureSession mCaptureSession;
    private CameraCharacteristics mCameraCharacteristics;
    /*** {@link CaptureRequest.Builder}用于相机预览请求的构造器*/
    private CaptureRequest.Builder mPreviewRequestBuilder;

    /***预览请求, 由上面的构建器构建出来*/
    private CaptureRequest mPreviewRequest;
    /**
     * 从屏幕旋转图片转换方向。
     */
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    com.tencent.cos.xml.CosXmlServiceConfig CosXmlServiceConfig = new CosXmlServiceConfig.Builder()
            .setAppidAndRegion(appid, region)
            .setDebuggable(true)
            .builder();

    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 90);
        ORIENTATIONS.append(Surface.ROTATION_90, 0);
        ORIENTATIONS.append(Surface.ROTATION_180, 270);
        ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }

    /***判断是否支持闪关灯*/
    private boolean mFlashSupported;

    /*** 用于运行不应阻塞UI的任务的附加线程。*/
    private HandlerThread mBackgroundThread;

    /*** 用于在后台运行任务的{@link Handler}。*/
    private Handler mBackgroundHandler;

    private String pcmPath = null;

    /**
     * 文件存储路径
     */

    /**
     * 预览请求构建器, 用来构建"预览请求"(下面定义的)通过pipeline发送到Camera device
     * 这是{@link ImageReader}的回调对象。 当静止图像准备保存时，将会调用“onImageAvailable”。
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.customcamera);
        //requestPermission();
        texture = (AutoFitTextureView) findViewById(R.id.texture);
        speak = (Button) findViewById(R.id.speak);
        but_cx=(Button) findViewById(R.id.but_cx);
        but_xyb=(Button) findViewById(R.id.but_xyb);

        speak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                captureStillPicture();
//                start();
            }

        });
        //点击返回上一页
        but_fan=(Button) findViewById(R.id.but_fan);
        but_fan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 给but_fan添加点击响应事件
                Intent intent = new Intent(CustomCamera.this, Main_Activity.class);
                //启动
                startActivity(intent);
            }
        });

    }

    //使用前面获取的拍照尺寸
    private final ImageReader.OnImageAvailableListener mOnImageAvailableListener = new ImageReader.OnImageAvailableListener() {

        @Override
        public void onImageAvailable(ImageReader reader) {
            //执行图像保存子线程
            mFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg");
            mBackgroundHandler.post(new ImageSaver(reader.acquireNextImage(), mFile));


        }

    };

    /*** {@link CameraDevice.StateCallback}打开指定摄像头回调{@link CameraDevice}*/
    private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {

        @Override
        public void onOpened(@NonNull CameraDevice cameraDevice) {
            //当camera成功打开之后会回调该方法。此时camera已经就绪，可以开始对相机进行一系列的操作，
            //可通过调用CameraCaptureSession.createCaptureSession方法来设置第一个capture session
            mCameraDevice = cameraDevice;
            createCameraPreview();
        }

        @Override
        public void onDisconnected(@NonNull CameraDevice cameraDevice) {
            //当camera不再可用，或调用CameraManager.openCamera()打开相机失败时都会
            //调用此方法.此时任何尝试调用CameraDevice方法的操作都会失败并抛出一个
            //CameraAccessException异常。
            //安全策略或权限的改变、可移动相机设备的物理断开、或者当该camera需要更高优
            //先级的camera API Client时都会导致该camera设备连接断开
            cameraDevice.close();
            cameraDevice = null;
        }

        @Override
        public void onError(@NonNull CameraDevice cameraDevice, int error) {
            //顾名思义。当camera出错时会回调该方法
            //应在该方法调用CameraDevice.close()和做一些其他释放相机资源的操作，防止相机出错而导致一系列问题。
            cameraDevice.close();
            cameraDevice = null;
        }
        @Override
        public void onClosed(@NonNull CameraDevice cameraDevice){
            super.onClosed(cameraDevice);
            //当调用CameraDevice.close()关闭相机设备后会回调此方法。camera为别关闭的相机设备。
            //该方法被回调执行后，任何尝试调用camera相关的操作都会失败，并且抛出一个IllegalStateException异常
        }

    };

    /**
     * TextureView 自定义相机生命周期响应
     */
    private final TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
        @SuppressLint("LongLogTag")
        @Override //创建
        public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
            //当TextureView创建完成，打开指定摄像头相机
            openCamera(width, height, mCameraId);

        }

        @Override //尺寸改变
        public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) {

        }

        @Override //销毁
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {

            return false;
        }

        @Override //更新
        public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {

        }
    };
    private int CONTROL_AE_MODE;


    /**
     * 打开指定摄像头ID的相机
     *
     * @param width
     * @param height
     * @param cameraId
     */
    private void openCamera(int width, int height, int cameraId) {
        if (ActivityCompat.checkSelfPermission(CustomCamera.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            return;
        }

        try {
            mSurfaceWidth = width;
            mSurfaceHeight = height;
//            Log.i("heeee",cameraId+"");
            getCameraId(cameraId);
            CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(mCameraId + "");
            StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            // 获取设备方向
            int rotation = getWindowManager().getDefaultDisplay().getRotation();
            int totalRotation = sensorToDeviceRotation(characteristics, rotation);
            boolean swapRotation = totalRotation == 90 || totalRotation == 270;
            int rotatedWidth = mSurfaceWidth;
            int rotatedHeight = mSurfaceHeight;
            if (swapRotation) {
                rotatedWidth = mSurfaceHeight;
                rotatedHeight = mSurfaceWidth;
            }
            // 获取最佳的预览尺寸
            mPreviewSize = getPreferredPreviewSize(map.getOutputSizes(SurfaceTexture.class), rotatedWidth, rotatedHeight);
            Log.d("143535","fsadkfj");
            if (swapRotation) {
                texture.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());

            } else {
                texture.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
            }
            if (mImageReader == null) {

                // 创建一个ImageReader对象，用于获取摄像头的图像数据,maxImages是ImageReader一次可以访问的最大图片数量
                mImageReader = ImageReader.newInstance(mPreviewSize.getWidth(), mPreviewSize.getHeight(),
                        ImageFormat.JPEG, 2);
                mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);
            }
            //检查是否支持闪光灯
            Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
            mFlashSupported = available == null ? false : available;
            mCameraManager.openCamera(mCameraId + "", mStateCallback, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置相机闪关灯模式
     *
     * @param AE_MODE 闪关灯的模式
     * @throws CameraAccessException
     */
    private void setFlashMode(int AE_MODE) {
        if (mFlashSupported) {
            this.CONTROL_AE_MODE = AE_MODE;
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, AE_MODE);
            if (AE_MODE == CaptureRequest.CONTROL_AE_MODE_OFF) {
                mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
            }
        }
        mPreviewRequest = mPreviewRequestBuilder.build();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    //setRepeatingRequest()控制预览 控制拍照的方法为capture()
                    mCaptureSession.setRepeatingRequest(mPreviewRequest,
                            null, mBackgroundHandler);
                    mPreviewRequestBuilder.build();
                } catch (CameraAccessException e) {
                    Log.e("fail", "Failed to start camera preview because it couldn't access camera", e);
                } catch (IllegalStateException e) {
                    Log.e("fail", "Failed to start camera preview.", e);
                }
            }
        }, 600);
    }

    /**
     * 创建预览对话
     */
    private void createCameraPreview() {
        try {
            // 获取texture实例
            SurfaceTexture surfaceTexture = texture.getSurfaceTexture();
            assert surfaceTexture != null;
            //我们将默认缓冲区的大小配置为我们想要的相机预览的大小。
            surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
            // 用来开始预览的输出surface
            Surface surface = new Surface(surfaceTexture);
            //创建预览请求构建器
            mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            //将TextureView的Surface作为相机的预览显示输出
            mPreviewRequestBuilder.addTarget(surface);
            //在这里，我们为相机预览创建一个CameraCaptureSession。
            mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()), new CameraCaptureSession.StateCallback() {
                        @Override
                        public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                            // 相机关闭时, 直接返回
                            if (null == mCameraDevice) {
                                return;
                            }
                            //会话准备就绪后，我们开始显示预览。
                            // 会话可行时, 将构建的会话赋给field
                            mCaptureSession = cameraCaptureSession;
                            //相机预览应该连续自动对焦。
                            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
                            //设置闪关灯模式
                            setFlashMode(CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
                        }

                        @Override
                        public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                            showToast("预览失败了");
                        }
                    }, null
            );
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 拍照时调用方法
     */
    private void captureStillPicture() {
        try {
            if (mCameraDevice == null) {
                return;
            }
            // 首先创建作为拍照的CaptureRequest.Builder
            mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            // 将imageReader的surface作为CaptureRequest.Builder的目标
            mPreviewRequestBuilder.addTarget(mImageReader.getSurface());

            setFlashMode(CONTROL_AE_MODE);
            // 停止连续取景
            mCaptureSession.stopRepeating();
            // 捕获静态图像

            mCaptureSession.capture(mPreviewRequestBuilder.build(), new CameraCaptureSession.CaptureCallback() {
                // 拍照完成时激发该方法
                @Override
                public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                    //重新打开预览
                    createCameraPreview();
                }
            }, null);
//            mCaptureSession.stopRepeating();
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取设备方向
     *
     * @param characteristics
     * @param deviceOrientation
     * @return
     */
    private static int sensorToDeviceRotation(CameraCharacteristics characteristics, int deviceOrientation) {
        int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        deviceOrientation = ORIENTATIONS.get(deviceOrientation);
        return (sensorOrientation + deviceOrientation + 360) % 360;
    }

    /**
     * 获取可用设备可用摄像头列表
     */
    private void getCameraId(int ID) {

        try {
            mCameraManager = (CameraManager)getSystemService(Context.CAMERA_SERVICE);
//            Log.i("hello",(mCameraManager.getCameraIdList()).length+"");
            for (String cameraId : mCameraManager.getCameraIdList()) {
                Log.i("hello",cameraId);
                CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId);
                if (characteristics.get(CameraCharacteristics.LENS_FACING) == ID) {
                    continue;
                }
                mCameraId = Integer.valueOf(cameraId);
                return;
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置最佳尺寸
     *
     * @param sizes
     * @param width
     * @param height
     * @return
     */
    private Size getPreferredPreviewSize(Size[] sizes, int width, int height) {
        Log.d("sizes[0]",width+""+height);
        List<Size> collectorSizes = new ArrayList<>();
        for (Size option : sizes) {
            if (width > height) {
                if (option.getWidth() > width && option.getHeight() > height) {
                    collectorSizes.add(option);
                }
            } else {
                if (option.getHeight() > width && option.getWidth() > height) {
                    collectorSizes.add(option);
                }
            }
        }
        if (collectorSizes.size() > 0) {
            return Collections.min(collectorSizes, new Comparator<Size>() {
                @Override
                public int compare(Size s1, Size s2) {
                    return Long.signum(s1.getWidth() * s1.getHeight() - s2.getWidth() * s2.getHeight());
                }
            });
        }

        return sizes[0];
    }



    /**
     * 初试化拍照线程
     */
    public void startBackgroundThread() {
        mBackgroundThread = new HandlerThread("Camera Background");
        mBackgroundThread.start();
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    }

    public void stopBackgroundThread() {
        if (mBackgroundThread != null) {
            mBackgroundThread.quitSafely();
            try {
                mBackgroundThread.join();
                mBackgroundThread = null;
                mBackgroundHandler = null;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Closes the current {@link CameraDevice}.
     * 关闭正在使用的相机
     */
    private void closeCamera() {
        // 关闭捕获会话
        if (null != mCaptureSession) {
            mCaptureSession.close();
            mCaptureSession = null;
        }
        // 关闭当前相机
        if (null != mCameraDevice) {
            mCameraDevice.close();
            mCameraDevice = null;
        }
        // 关闭拍照处理器
        if (null != mImageReader) {
            mImageReader.close();
            mImageReader = null;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        startBackgroundThread();
        if (texture.isAvailable()) {
            openCamera(texture.getWidth(), texture.getHeight(), mCameraId);
        } else {
            texture.setSurfaceTextureListener(textureListener);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        closeCamera();
        stopBackgroundThread();
    }


//    public void onViewClicked() {
//        captureStillPicture();
//    }

    /**
     * Shows a {@link Toast} on the UI thread.
     * 在UI上显示Toast的方法
     *
     * @param text The message to show
     */
    /**
     * Shows a {@link Toast} on the UI thread.
     * 在UI上显示Toast的方法
     *
     * @param text The message to show
     */
    private void showToast(final String text) {
        runOnUiThread(() -> Toast.makeText(CustomCamera.this, text, Toast.LENGTH_SHORT).show());
    }


    /**
     * Saves a JPEG {@link Image} into the specified {@link File}.
     * 保存图片到自定目录
     * 保存jpeg到指定的文件夹下, 开启子线程执行保存操作
     */
    private class ImageSaver implements Runnable {

        ImageSaver(Image image, File file) {
            mImage = image;
            mFile = file;
        }

        @Override
        public void run() {
            //getPreviewDegree(CustomCamera.this);
            ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            FileOutputStream output = null;
            try {
                output = new FileOutputStream(mFile);
                output.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                mImage.close();
                if (null != output) {
                    try {
                        output.close();
                        mFilePath = mFile.getAbsolutePath();

//                        editPhoto(mFilePath);//调整图片的角度
                        //distinguishPhoto(mFilePath);//识别本地的图片
                        uploadPhoto(mFilePath);//上传图片到腾讯云服务器上
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

    }


    //上传到腾讯云cos
    public void uploadPhoto(String mFilePath) {
        String fileName=mFilePath.substring(29);
        QCloudCredentialProvider QCloudCredentialProvider = new ShortTimeCredentialProvider("AKIDERadYMzb5OXXQ9EIguW5ZyJZjnldt5gC", "fFesvnkXAe0IPL5d1EG6lHcv57zgDZkk", 300);
        Log.i("&&&&&", QCloudCredentialProvider.toString());
        CosXmlService CosXmlService = new CosXmlService(this, CosXmlServiceConfig, QCloudCredentialProvider);
        UploadService.ResumeData uploadData = new UploadService.ResumeData();
        uploadData.bucket = "huihu-1256678596";
        uploadData.cosPath = fileName; //格式如 cosPath = "test.txt";
        uploadData.srcPath = mFilePath; // 如 srcPath =Environment.getExternalStorageDirectory().getPath() + "/test.txt";
        uploadData.sliceSize = 1024 * 1024; //每个分片的大小
        uploadData.uploadId = null; // 若是续传，则uploadId不为空
        UploadService uploadService = new UploadService(CosXmlService, uploadData);
        uploadService.setProgressListener(new CosXmlProgressListener() {
            @Override
            public void onProgress(long progress, long max) {
                // todo Do something to update progress...
            }
        });
        /**
         * 开始上传
         */
        try {
            CosXmlResult cosXmlResult = uploadService.upload();
            Log.i("上传的结果", cosXmlResult.toString());
            Log.i("****", cosXmlResult.printResult());
            Log.i("++++", cosXmlResult.accessUrl);
            postFile(cosXmlResult.accessUrl);
        } catch (CosXmlClientException e) {
            // mProgressDialog.dismiss();
            e.printStackTrace();
            try {
                Toast.makeText(CustomCamera.this, "上传失败，请检查您的网络连接！", Toast.LENGTH_SHORT).show();
                return;
            } catch (Exception e1) {
                Looper.prepare();
                Toast.makeText(CustomCamera.this, "上传失败，请检查您的网络连接！", Toast.LENGTH_SHORT).show();
                Looper.loop();
                return;
            }
        } catch (CosXmlServiceException e2) {
            //mProgressDialog.dismiss();
            e2.printStackTrace();
            try {
                Toast.makeText(CustomCamera.this, "上传失败！", Toast.LENGTH_SHORT).show();
                return;
            } catch (Exception e1) {
                Looper.prepare();
                Toast.makeText(CustomCamera.this, "上传失败！", Toast.LENGTH_SHORT).show();
                Looper.loop();
                return;
            }
        } catch (Exception e3) {
            e3.printStackTrace();
            try {
                Toast.makeText(CustomCamera.this, "服务正在升级...，请稍后再试！", Toast.LENGTH_SHORT).show();
                return;
            } catch (Exception e1) {
                Looper.prepare();
                Toast.makeText(CustomCamera.this, "服务正在升级...，请稍后再试！", Toast.LENGTH_SHORT).show();
                Looper.loop();
                return;
            }
        }
    }
    //上传图片到腾讯云服务器上
    public void postFile(String accessUrl) {
//        File bitmap = new File(mPhotoUri.getPath());
        POST_URL="http://47.92.219.50:5000/znsz3?imgpath=";
        final String cosUrl = "https://"+accessUrl;
        imgUriInNet=cosUrl;//获取图片在服务器上的地址
        Log.i("accessUrl",cosUrl);
        new Thread(new Runnable() {
            //            String cosUrl = "https://"+accessUrl;
            @Override
            public void run(){
                try {
                    OkHttpUtil.postFile(POST_URL, null, postFileCallback, cosUrl);
                }catch (Exception e){
                    // mProgressDialog.dismiss();
                    e.printStackTrace();
                    try {
                        Toast.makeText(CustomCamera.this, "当前服务繁忙，请稍后再试！", Toast.LENGTH_SHORT).show();
                        return;
                    }catch (Exception e1){
                        Looper.prepare();
                        Toast.makeText(CustomCamera.this, "当前服务繁忙，请稍后再试！", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                        return;
                    }
                }
            }
        }).start();
    }
    private Callback postFileCallback = new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            //mProgressDialog.dismiss();
            try {
                Toast.makeText(CustomCamera.this, R.string.post_fail, Toast.LENGTH_SHORT).show();
            } catch (Exception e1) {
                Looper.prepare();
                Toast.makeText(CustomCamera.this, R.string.post_fail, Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response != null) {
                //mProgressDialog.dismiss();
                if (response.message().equals("OK")) {
                    Looper.prepare();
                    Toast.makeText(CustomCamera.this, "上传成功！", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }
            }

        }
    };
}
